package com.rabbitmq.delay;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.util.ConnectionUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.common.Constant.NUM64;

// 延时消费,通过在正常队列中设置消息TTL为10秒实现延迟
public class DelayQueue {
    public static void main(String[] args) throws IOException,
            TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.basicQos(NUM64);
        Consumer consumer = new DefaultConsumer(channel) {
            // 监听死信队列，如果死信队列有消息，就会对死信队列的消息进行消费，此时死信队列可以看作是延迟队列
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
                    throws IOException {
                System.out.println(" recv message: " + new String(body));
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume("queue.dlx", consumer);
    }
}
